package org.jetnuke.modules.blog;

import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.velocity.VelocityContext;
import org.jetnuke.common.ActionForward;
import org.jetnuke.common.IAction;
import org.jetnuke.common.IAdminInfo;
import org.jetnuke.common.IModuleInfo;
import org.jetnuke.common.IUserInfo;
import org.jetnuke.dao.BlogCommentDAO;
import org.jetnuke.dao.BlogPostDAO;
import org.jetnuke.dao.DataAccessDriver;
import org.jetnuke.entities.BlogComment;
import org.jetnuke.entities.BlogPost;
import org.jetnuke.util.JetUtil;
import org.jetnuke.util.StringUtils;

public class Trackback implements IAction {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(Trackback.class);

	static String okResponse = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
			+ "<response>\n" + "<error>0</error>\n" + "</response>";
	static String errorResponse1 = " <?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
			+ "<response>\n" + "<error>1</error>\n" + "<message>";
	static String errorResponse2 = "</message>\n</response>";
	int id;
	String url, title = "", excerpt = "", blog_name = "";

	public ActionForward exec(HttpServletRequest request,
			HttpServletResponse response, VelocityContext vc, IModuleInfo info,
			String op, IUserInfo ui, IAdminInfo ai) throws Exception {
		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - start"); //$NON-NLS-1$
		}

		if (!("POST".equalsIgnoreCase(request.getMethod())))
			return null;

		String contentType = request.getContentType();
		if (contentType != null) {
			if (!contentType.toLowerCase().trim().startsWith(
					"application/x-www-form-urlencoded")) {
				JetUtil.redirect(vc, response, request.getContextPath() + "");

				if (logger.isDebugEnabled()) {
					logger
							.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
				}
				return null;

			}
		}
		// if(!("application/x-www-form-urlencoded".equalsIgnoreCase(contentType))){
		// return null;
		// }
		if (url == null) {
			// If it doesn't look like a trackback at all...
			JetUtil.redirect(vc, response, request.getContextPath() + "");

			if (logger.isDebugEnabled()) {
				logger
						.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
			}
			return null;
		}
		response.addHeader("Content-Type", "text/xml");
		response.addHeader(" charset", "UTF-8");

		BlogPostDAO bpm = DataAccessDriver.getInst().newBlogPostDAO();
		BlogPost bp = bpm.retrieveByPK(id);
		if (bp.getID() != id) {
			String error = "I really need an ID for this to work.";
			sendErrorMessage(error, response);

			if (logger.isDebugEnabled()) {
				logger
						.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
			}
			return null;

		}
		if (!"open".equals(bp.getPINGSTATUS())) {
			String error = "Sorry, trackbacks are closed for this item.";
			sendErrorMessage(error, response);

			if (logger.isDebugEnabled()) {
				logger
						.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
			}
			return null;
		}
		BlogCommentDAO bcm = DataAccessDriver.getInst().newBlogCommentDAO();
		List commentByPostList = bcm.selectByPostID(id);
		Iterator it = commentByPostList.iterator();
		while (it.hasNext()) {
			BlogComment bc = (BlogComment) it.next();
			if ("trackback".equals(bc.getTYPE())
					&& url.equals(bc.getAUTHOR_URL())) {
				String error = "We already have a ping from that URI for this post.";
				sendErrorMessage(error, response);

				if (logger.isDebugEnabled()) {
					logger
							.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
				}
				return null;
			}
		}

		BlogComment bc = new BlogComment();
		String ua = request.getHeader("user-agent");
		if (ua == null)
			ua = "";
		String ip = request.getRemoteAddr();
		if (ip == null)
			ip = "";
		bc.setAUTHOR(blog_name);
		bc.setAGENT(ua);

		bc.setAUTHOR_EMAIL("");
		bc.setAUTHOR_IP(ip);
		bc.setAUTHOR_URL(url);
		String comment = "<strong>" + title + "</strong><br/>" + excerpt;
		bc.setCONTENT(comment);
		bc.setDATE(new GregorianCalendar().getTime());
		bc.setPARENT(0);
		bc.setPOST_ID(id);
		bc.setTYPE("trackback");
		int uid = 1;

		String approved = "0";
		// if(uid==bp.getAID())
		approved = "1"; // TODO give more flexibility!!
		bc.setAPPROVED(approved);
		bc.setUSER_ID(uid);

		bcm.addNew(bc);
		response.getWriter().write(okResponse);

		if (logger.isDebugEnabled()) {
			logger
					.debug("exec(HttpServletRequest, HttpServletResponse, VelocityContext, IModuleInfo, String, IUserInfo, IAdminInfo) - end"); //$NON-NLS-1$
		}
		return null;
	}

	private void sendErrorMessage(String errorMessage,
			HttpServletResponse response) throws IOException {
		if (logger.isDebugEnabled()) {
			logger
					.debug("sendErrorMessage(String, HttpServletResponse) - start"); //$NON-NLS-1$
		}

		String finalString = errorResponse1 + errorMessage + errorResponse2;
		response.getWriter().write(finalString);

		if (logger.isDebugEnabled()) {
			logger.debug("sendErrorMessage(String, HttpServletResponse) - end"); //$NON-NLS-1$
		}
	}

	public void setBlog_name(String blog_name) {
		if (logger.isDebugEnabled()) {
			logger.debug("setBlog_name(String) - start"); //$NON-NLS-1$
		}

		this.blog_name = StringUtils.filterText(blog_name, true);

		if (logger.isDebugEnabled()) {
			logger.debug("setBlog_name(String) - end"); //$NON-NLS-1$
		}
	}

	public void setExcerpt(String excerpt) {
		if (logger.isDebugEnabled()) {
			logger.debug("setExcerpt(String) - start"); //$NON-NLS-1$
		}

		this.excerpt = StringUtils.filterText(excerpt, true);
		if (excerpt.length() > 255) {
			excerpt = excerpt.substring(0, 252) + "...";
		}

		if (logger.isDebugEnabled()) {
			logger.debug("setExcerpt(String) - end"); //$NON-NLS-1$
		}
	}

	public void setId(int id) {
		this.id = id;
	}

	public void setTitle(String title) {
		if (logger.isDebugEnabled()) {
			logger.debug("setTitle(String) - start"); //$NON-NLS-1$
		}

		this.title = StringUtils.filterText(title, true);

		if (logger.isDebugEnabled()) {
			logger.debug("setTitle(String) - end"); //$NON-NLS-1$
		}
	}

	public void setUrl(String url) {
		this.url = url;
	}

}
